package com.stone.ai.robot.controller;

import ch.qos.logback.core.util.StringUtil;
import io.micrometer.common.util.StringUtils;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.deepseek.DeepSeekAssistantMessage;
import org.springframework.ai.deepseek.DeepSeekChatModel;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;

@RestController
@RequestMapping("/ai/r1")
public class DeepSeekR1ChatController {

    @Resource
    private DeepSeekChatModel  deepSeekChatModel;


    // 使用原子布尔值跟踪分隔线状态（每个请求独立）
    AtomicBoolean needSeparator = new AtomicBoolean(true);


    @GetMapping("/deepseek/generate")
    public String generate(@RequestParam(value = "message", defaultValue = "你是谁")String message) {
        return deepSeekChatModel.call(message);
    }
    //流式回复
    @GetMapping(value = "/deepseek/generateStream",produces = "text/html;charset=utf-8")
    public Flux<String> generateStream(@RequestParam(value = "message", defaultValue = "你是谁")String message) {
        Prompt prompt = new Prompt(new UserMessage(message));
        return deepSeekChatModel.stream(prompt)
                .mapNotNull(chatResponse -> {
                    //获取响应式内容
                    DeepSeekAssistantMessage    assistantMessage= (DeepSeekAssistantMessage)chatResponse.getResult().getOutput();
                    //推理内容
                    String reasoningContent = assistantMessage.getReasoningContent();
                    //正式回答
                    String text = assistantMessage.getText();

                    //是否正式内容
                    boolean isTextResponse = false;

                    String rewContent;
                    if (Objects.isNull(text)){
                        rewContent=reasoningContent;
                    }else {
                        rewContent=text;
                        isTextResponse=true;
                    }
//                    String processed = StringUtils.isNotBlank(reasoningContent) ? reasoningContent : text;

                    //处理换行
                    String processed = StringUtils.isNotBlank(rewContent) ? rewContent.replace("\n", "<br>") : text;

                    if(isTextResponse &&needSeparator.compareAndSet(true,false) ) {
                        processed = "<hr>"+processed;
                    }
                    return processed;
                });
    }
}
